package com.songlanyun.modules.schedule;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.songlanyun.modules.comment.model.vo.OrderGoodsCommentVO;
import com.songlanyun.modules.comment.service.OrderGoodsCommentService;
import com.songlanyun.modules.goods.entity.Goods;
import com.songlanyun.modules.goods.service.GoodsService;
import com.songlanyun.modules.shop.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 定时任务
 * <p>
 * 定时更新评价星级平均分
 */
@Component
@Configuration
@EnableScheduling
@Lazy(false)
@Slf4j
public class CommentScheduleServiceImpl {

    @Resource
    private OrderGoodsCommentService orderGoodsCommentService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private ShopService shopService;

    /**
     * 每天三点商家、商品 评价星级平均分
     * 商家、商品
     * 评价星级平均分
     */
    @Async
    @Scheduled(cron = "0 0 3 * * ?")
//    @Scheduled(cron = "0/5 * * * * ? ")
    public void commentAvgTask() {
        //计算商家所有评价的平均分
        List<OrderGoodsCommentVO> goodsAvgs = orderGoodsCommentService.getAvgByGoods();
        //更新商家平均分
        goodsAvgs.forEach(g -> {
            goodsService.updateAverageById(g.getGoodsId(), g.getAverage());
        });

        //计算商品所有评价的平均分
        List<OrderGoodsCommentVO> shopAvgs = orderGoodsCommentService.getAvgByShop();
        //更新商品平均分
        shopAvgs.forEach(s -> {
            shopService.updateAverageById(s.getShopId(), s.getAverage());
        });

    }
}
